package com.kingcore.director.setting.ui;

import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;

import wzw.beans.DbBean;
import wzw.sql.DatabaseOperator;
import wzw.util.ComponentUtil;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.core.ui.ProcessingDialog;
import com.kingcore.director.setting.bean.FilesBackupBean;
import com.kingcore.framework.context.ApplicationContext;
import com.sunking.swing.JDirChooser;
import com.sunking.swing.JNumberField;

public class FileBackupPanel extends JPanel  implements DatabaseOperator, ActionListener{

	private JLabel jLabel = null;
	private JLabel jLabel1 = null;
	private JLabel jLabel2 = null;
	private JTextField interval = null;
	private JTextField destPah = null;
	private JComboBox currentSort = null;
	private JButton btnSave = null;
	private JLabel jLabel3 = null;
	private JComboBox hour = null;
	private JComboBox minute = null;
	private JLabel jLabel4 = null;
	private JLabel jLabel5 = null;
	private JLabel jLabel6 = null;
	private JLabel jLabel7 = null;
	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getInterval() {
		if (interval == null) {
			interval = new JNumberField(3);		//JTextField
			interval.setBounds(new java.awt.Rectangle(159,63,155,23));
		}
		return interval;
	}

	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getDestPath() {
		if (destPah == null) {
			destPah = new JTextField();
			destPah.setBounds(new java.awt.Rectangle(159,95,155,23));
		}
		return destPah;
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getCurrentSort() {
		if (currentSort == null) {
			currentSort = new JComboBox();
			currentSort.setBounds(new java.awt.Rectangle(159,127,155,23));
			ComponentUtil.initComboBox( currentSort,"SELECT VAL,TXT,isDefault FROM "+DirectorConstants.SYS_Class+" WHERE LBBH='000002'");
		}
		return currentSort;
	}
	

	private JButton currentSortExecute = null;
	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JButton getCurrentSortExecute() {
		if (currentSortExecute == null) {
			currentSortExecute = new JButton();
			currentSortExecute.setText("马上备份"); //比"马上执行"表意明白
			currentSortExecute.setBounds(new java.awt.Rectangle(318,127,90,23));
			currentSortExecute.addActionListener(this);
		}
		return currentSortExecute;
	}
	
	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnSave() {
		if (btnSave == null) {
			btnSave = new JButton();	//  new ImageIcon("E:/Woo_Java/apps_src/Prj_wzwen_director/build/resource/irector.ico")
			/// 要设置图片，需要使用 this.getClass().getResource(...)，而且图片文件需要放在class编译之后所在的路径；
			///System.out.println(this.getClass().getResource("exit1.gif")==null);
			///btnSave.setIcon( new ImageIcon( this.getClass().getResource("exit1.gif") ) );
			///new URL();
			btnSave.setText("...");
			btnSave.setBounds(new java.awt.Rectangle(315,94,24,22));
			btnSave.addActionListener(this);
		}
		return btnSave;
	}

	/**
	 * This method initializes hour	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getHour() {
		if (hour == null) {
			hour = new JComboBox();
			hour.setBounds(new java.awt.Rectangle(192,31,59,23));
			for (int i = 1; i < 25; i++) {
				hour.addItem( i+"" );
			}
			hour.setSelectedItem("12");
		}
		return hour;
	}

	/**
	 * This method initializes minute	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getMinute() {
		if (minute == null) {
			minute = new JComboBox();
			minute.setBounds(new java.awt.Rectangle(274,31,57,23));
			for (int i = 0; i < 10; i++) {
				minute.addItem( "0"+i );
			}
			for (int i = 10; i < 61; i++) {
				minute.addItem( ""+i );
			}
			minute.setSelectedItem("15");
		}
		return minute;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	Dialog mainDialog = null;
	/**
	 * This is the default constructor
	 * @param dialog 
	 */
	public FileBackupPanel(Dialog dialog) {
		super();
		this.mainDialog = dialog;
		initialize();
		
		try {
			this.fetchData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		jLabel7 = new JLabel();
		jLabel7.setBounds(new java.awt.Rectangle(317,64,85,18));
		jLabel7.setText("(单位为小时)");
		jLabel6 = new JLabel();
		jLabel6.setBounds(new java.awt.Rectangle(332,31,92,23));
		jLabel6.setText("分 执行备份");
		jLabel5 = new JLabel();
		jLabel5.setBounds(new java.awt.Rectangle(254,31,18,23));
		jLabel5.setText("时");
		jLabel4 = new JLabel();
		jLabel4.setBounds(new java.awt.Rectangle(159,31,35,23));
		jLabel4.setText("每天");
		jLabel3 = new JLabel();
		jLabel3.setBounds(new java.awt.Rectangle(15,31,125,23));
		jLabel3.setText("备份执行时间：");
		jLabel2 = new JLabel();
		jLabel2.setBounds(new java.awt.Rectangle(15,127,131,23));
		jLabel2.setText("当前启用的备份类别：");
		jLabel1 = new JLabel();
		jLabel1.setBounds(new java.awt.Rectangle(15,95,131,23));
		jLabel1.setText("备份目标路径：");
		jLabel = new JLabel();
		jLabel.setBounds(new java.awt.Rectangle(15,63,131,23));
		jLabel.setText("全备份间隔数：");
		this.setLayout(null);
		this.setSize(500, 392);
		this.add(jLabel, null);
		this.add(jLabel1, null);
		this.add(jLabel2, null);
		this.add(getInterval(), null);
		this.add(getDestPath(), null);
		this.add(getCurrentSort(), null);
		this.add(getCurrentSortExecute(), null);
		this.add(getBtnSave(), null);
		this.add(jLabel3, null);
		this.add(getHour(), null);
		this.add(getMinute(), null);
		this.add(jLabel4, null);
		this.add(jLabel5, null);
		this.add(jLabel6, null);
		this.add(jLabel7, null);
	}


	public boolean saveData() throws SQLException {
		DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
		try {
			List<String> l_sql=new ArrayList<String>();
			
			l_sql.add( "UPDATE "+DirectorConstants.SYS_Setting+" SET VAL='"+ ComponentUtil.getSelectedItemCode( getCurrentSort() ) + "' " +
					"Where KEY='"+DirectorConstants.File_Backup_CurrentSort+"'" );
			l_sql.add( "UPDATE "+DirectorConstants.SYS_Setting+" SET VAL='"+getInterval().getText() + "' " +
					"Where KEY='"+DirectorConstants.File_Backup_Interval+"'" );
			l_sql.add( "UPDATE "+DirectorConstants.SYS_Setting+" SET VAL='"+getDestPath().getText() + "' " +
					"Where KEY='"+DirectorConstants.File_Backup_DestPath+"'" );
			String ts_time = hour.getSelectedItem() + ":" + minute.getSelectedItem() ;
			l_sql.add( "UPDATE "+DirectorConstants.SYS_Setting+" SET VAL='"+ ts_time + "' " +
					"Where KEY='"+DirectorConstants.File_Backup_Time+"'" );
			dbBean.executeBatch(l_sql);
			
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		
	}

	/**
	 * 
	 *  也可以使用下面的实现方法：
	  	//step
	  	DbBean dbBean = new DbBean();
	  	String sql =  "SELECT VAL FROM "+DirectorConstants.SYS_Setting +
	  					    " Where KEY='"+DirectorConstants.File_Backup_CurrentSort+"'" ;
	  	String defaultType = dbBean.queryForString(sql);
	 *			
	 */
	public boolean fetchData() throws SQLException {

		String sql="";
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
			conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
			stmt=conn.createStatement();
			sql =  "SELECT VAL FROM "+DirectorConstants.SYS_Setting +
					" Where KEY='"+DirectorConstants.File_Backup_CurrentSort+"'" ;
			rs=stmt.executeQuery(sql);
			if (rs.next()) {
				ComponentUtil.setSelectedItemByCode( getCurrentSort(), rs.getString("VAL"));
			}
			
			sql =  "SELECT VAL FROM "+DirectorConstants.SYS_Setting +
					" Where KEY='"+DirectorConstants.File_Backup_Interval+"'" ;
			rs=stmt.executeQuery(sql);
			if (rs.next()) {
				getInterval().setText( rs.getString("VAL"));
			}
			
			sql =  "SELECT VAL FROM "+DirectorConstants.SYS_Setting +
					" Where KEY='"+DirectorConstants.File_Backup_DestPath+"'" ;
			rs=stmt.executeQuery(sql);
			if (rs.next()) {
				getDestPath().setText( rs.getString("VAL"));
			}

			sql =  "SELECT VAL FROM "+DirectorConstants.SYS_Setting +
					" Where KEY='"+DirectorConstants.File_Backup_Time+"'" ;
			rs=stmt.executeQuery(sql);
			if (rs.next()) {
				String ts_time = rs.getString("VAL");
				String ts_hour = ts_time.substring(0, ts_time.indexOf(":") );
				String ts_minute = ts_time.substring( ts_time.indexOf(":")+1 );
				hour.setSelectedItem(ts_hour);
				minute.setSelectedItem(ts_minute);
			}

		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(this,e1.getMessage(),"查询失败",JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();						
		} finally{
			//释放资源
			wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
		}
		return true;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Object eventObj = e.getSource();
		if (eventObj==currentSortExecute) {
			final String destPath = getDestPath().getText();
			if (StringUtils.isBlank(destPath)) {
				JOptionPane.showMessageDialog(this, "请先设置备份目标路径！", "提示", JOptionPane.INFORMATION_MESSAGE);
				getDestPath().requestFocus();
				return;
			}
			if(JOptionPane.showConfirmDialog(this,"确认马上将当前所选类别备份至["+destPath+"]吗？", "提示",JOptionPane.OK_CANCEL_OPTION) //"确认复制所有文件，并且确认当前系统时间准确吗？"
					!=JOptionPane.OK_OPTION)
				return;
			final String backupSort = ComponentUtil.getSelectedItemCode( getCurrentSort() );
			final JPanel l_parent = this;
			//实现正在处理...效果
			//下面是种非多线程方式的尝试
//			final ImageIcon img = new ImageIcon("./resource/processing.gif");  
//			JLabel jLabel71 = new JLabel("fdsafdsfdsafdsf" );
//			jLabel71.setBounds(new java.awt.Rectangle(52,64,85,85));
//			this.add(jLabel71);
//			this.repaint();
			
			Thread thread = new Thread(){
				public void run(){
					try {
						FilesBackupBean.executeBackup(destPath, backupSort, null);
						JOptionPane.showMessageDialog(l_parent, "执行备份成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception e) {
						e.printStackTrace();
						JOptionPane.showMessageDialog(null,e.getMessage(),"执行备份失败",JOptionPane.ERROR_MESSAGE);
					}
				}
			};
			
			ProcessingDialog.showInstance(this.mainDialog, thread ,
						"正在执行，请等待......");//启动等待提示框线程,能否把现实做为线程，对其他代码改动下？
			
		} else if(eventObj==btnSave){
	        File f = JDirChooser.showDialog( getDestPath().getParent(), "Please Select directory", true, null,
	                                        "Please Select");
	        if(f != null){
	        	String ts_path=f.getAbsolutePath();
	        	//ts_path = ts_path.replace("\\","/"); //by wzw:keep as same as File.separator
	        	getDestPath().setText( ts_path + File.separator );	// 以/结尾
	        }
		}
		
	}
	
}  //  @jve:decl-index=0:visual-constraint="10,10"
